/*
 * File:   uart.c
 * Author: Marcel
 *
 * Created on 01. September 2012, 22:36
 */

#include <p18f2620.h>
#include <delays.h>
#include <usart.h>
#include <stdlib.h>
#include "uart.h"


void uart_init(void) {
    OpenUSART (USART_TX_INT_OFF &
               USART_RX_INT_ON &
               USART_ASYNCH_MODE &
               USART_EIGHT_BIT &
               USART_CONT_RX &
               USART_BRGH_LOW,  12);    // 8n1 9600
    IPR1bits.RCIP = 1;

    #ifdef UART_OUTPUT
    uart_putrs((const far rom char*) "\n\r\n\r/----------------------------------\\\n\r"
                                             "|         Service Terminal!        |\n\r"
                                             "|          by MvK   08/12          |\n\r"
                                            "\\----------------------------------/\n\r");
    #endif
}

void uart_isr(void) {
    putcUSART(ReadUSART());
}

void uart_putc(unsigned char c) {
    INTCONbits.GIEL = 0;    // Enable all low priority interrupts
    putcUSART(c);
    while(TXSTAbits.TRMT == 0);
    INTCONbits.GIEL = 1;    // Enable all low priority interrupts
}

void uart_puts(char* s) {
    INTCONbits.GIEL = 0;
    while(*s) {
        uart_putc(*s);
        s++;
    }
    INTCONbits.GIEL = 1;
}

void uart_putrs(const far rom char* s) {
    while(*s) {
        uart_putc(*s);
        s++;
    }
}

void uart_puti(int i) {
    char buf[6];
    itoa(i, buf);
    uart_puts(buf);
}

void uart_putb(unsigned char c) {
    char buf[4];
    btoa(c, buf);
    uart_puts(buf);
}


void uart_puthex(unsigned char c) {
    static const rom unsigned char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    uart_putc((const rom unsigned char) hex[(c & 0xF0) >> 4]);
    uart_putc((const rom unsigned char) hex[c & 0x0F]);
}